<style scoped>
</style>
<template>
  <div class="page-wrapper">
    <div class="page-wrapper__body">
      <div class="page-container is-form" v-loading="isLoading">
        <el-form ref="roleForm" :model="form" :rules="rules" label-position="top">
          <div class="block-title"><i>¶</i> 角色信息</div>
          <el-form-item label="角色名称" prop="name" required>
            <el-input v-model="form.name" maxlength="20" placeholder="请输入角色名称" ></el-input>
          </el-form-item>
          <el-form-item label="角色说明">
            <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入角色说明"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="block-title"><i>¶</i> 权限配置</div>
          </el-form-item>
<!--          <el-form-item>-->
    <!--        <el-tree :data="menuList" show-checkbox node-key="id"-->
    <!--                ref="tree" :props="defaultProps" default-expand-all highlight-current >-->
    <!--        </el-tree>-->
<!--          </el-form-item>-->
          <el-table border class="grid-table" v-loading="isLoading" width="100%"
                    :data="menuList" :span-method="objectSpanMethod">
            <el-table-column label="#" align="center" width="60">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checkedAll" :indeterminate="scope.row.indeterminate" @change="onNodeCheckAll(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="菜单组" align="left" min-width="150">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="onNodeCheck(scope.row)">{{scope.row.title}}</el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="菜单" align="left" min-width="200">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="onNodeCheck(scope.row)">{{scope.row.title}}</el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <div class="form-footer">
      <el-button type="primary" @click="onSubmit" style="width:120px;">保存</el-button>
      <el-button @click="$router.go(-1)">取 消</el-button>
    </div>
  </div>
</template>

<script>
  import MRole from '../../model/adminRole/index';
  import {findDetail,save} from "../../api/adminRole";
  import {findList} from "../../api/adminMenu";

  export default{
    data(){
      return{
        menuList:[],
        dataList:[],
        form:this.baseUtil.modelCopy(MRole),
        params:{
          id:0
        },
        isLoading:false,
        rules:{
          name:[{ required: true, message: '请输入角色名称', trigger: 'blur' }]
        },
        defaultProps: {
          children: 'children',
          label: 'title',
        },
      }
    },
    methods:{
      objectSpanMethod({ row, column, rowIndex, columnIndex }){
        //console.log("--==-->",row, column, rowIndex, columnIndex)
        if(columnIndex == 0 || columnIndex == 1){
          let span = {
            rowspan : row.rowspan,
            colspan : 1
          }
          if(columnIndex == 1){
            span.colspan = row.children==1?2:1;
          }
          return span;
        }
        if(row.children>0){
          return {
            rowspan:0,
            colspan:0
          }
        }
        return {
          rowspan: 1,
          colspan: 1
        };
      },
      onNodeCheckAll(node){
        console.log("==checkedAll==>",node.checkedAll)
        node.indeterminate = false;
        this.menuList.map(m=>{
          if((m.id == node.id ||m.parentCode == node.id) && m.checked == !node.checkedAll){
            m.checked = node.checkedAll;
            m.indeterminate = false;
          }
        })
      },
      onNodeCheck(node){
        let all = []
        let parentNode = node;
        if(node.parentCode>0) {
          parentNode = this.menuList.find(m=>m.id == node.parentCode);
          this.menuList.map(m => {
            if(m.id == node.parentCode){
              if(!node.checked && this.menuList.filter(n=>n.parentCode == node.parentCode && n.checked).length > 0) {
                return m;
              }
              m.checked = node.checked;
            }
          })
        }else{
          if(!node.checked){
            this.menuList.map(m=>{
              if(m.parentCode == node.id) m.checked = node.checked;
            })
          }
          //若只有一个子菜单.默认同步级联
          if(node.children <= 1){
            this.menuList.map(m=>{
              if(m.parentCode == node.id) m.checked = node.checked;
            })
          }
        }
        all = this.menuList.filter(m=>(m.id == parentNode.id ||m.parentCode == parentNode.id) && m.checked == node.checked)
        if(all.length == (parentNode.children+1)) {
          parentNode.indeterminate = false;
          parentNode.checkedAll = node.checked;
        }else{
          parentNode.indeterminate = true;
        }
      },
      onSubmit(){
        this.isLoading = true;
        this.$refs['roleForm'].validate((valid) => {
          if (valid) {
            this.handleSubmit();
          } else {
            this.isLoading = false;
            return false;
          }
        });
      },
      async handleSubmit(){
        let form = this.baseUtil.modelCopy(this.form);
         // form.menuIds = this.$refs.tree.getCheckedKeys();
          form.menuIds = this.menuList.filter(m=>m.checked).map(m=>m.id);
          console.log("===>",form.menuIds)
        let resp = await save(form);
        this.isLoading = false;
        if(!this.qUtil.validResp(resp)){
          this.$alert('保存失败!', '提示', { confirmButtonText: '确定'});
          return false;
        }
        this.$alert('保存成功!', '提示', { confirmButtonText: '确定',callback:()=>{
          this.$router.push("/roleList");
          }});

      },
      async loadData(){
        this.isLoading = true;
        if(this.params.id>0) {
          let resp = await findDetail(this.params.id);
          if (!this.qUtil.validResp(resp)) {
            this.$message.error('加载角色信息失败!');
            return false;
          }
          this.form = resp.data.model;
          // this.$refs.tree.setCheckedKeys(resp.data.model.menuIds);
          let menuIds = resp.data.model.menuIds || [];
          if (this.menuList.length > 0 && menuIds.length > 0) {
            this.menuList.map(m => {
              m.checked = menuIds.includes(m.id);
              if (m.parentCode == 0) {
                let nodes = this.menuList.filter(n => (n.id == m.id || n.parentCode == m.id) && menuIds.includes(n.id));
                m.checkedAll = nodes.length == (m.children + 1);
                m.indeterminate = m.children <= 1 ? false : !(nodes.length == 0 || m.checkedAll);
              }
            })
          }
        }
        this.isLoading = false;
      },
      async loadAllMenu(){
        let resp = await  findList();
        if(!this.qUtil.validResp(resp)){
          this.$message.error('加载权限菜单查询失败!');
          return false;
        }
        let list = resp.data.dataList || [];
        let result = [],n,len=0;
        list.map(m=>{
          len = m.children?m.children.length:0;
          n = this.baseUtil.modelCopy(m)
          n.children = len;
          n.rowspan=len>0?len+1:1;
          n.checked = false;
          n.indeterminate = false;
          result.push(n);
          if(len>0){
            m.children.forEach((c,i)=>{
              c.parentNode = m;
              c.children = 0;
              c.rowspan = 0;
              c.checked = false;
              c.indeterminate = false;
              result.push(c);
            })
          }
        })
        this.menuList = result;
      },
    },
    async mounted(){
      this.params.id = this.$route.params.id || 0;
      await this.loadAllMenu();
      this.loadData();

    }
  }
</script>